<template>
  <section class="inner-bottom-exp">
    <el-row :gutter="20">
      <el-col :span="6">
        <div class="inner-bottom-exp-inner">
          <div style="text-align: center;">
          </div>
          <el-tree :data="treeData" ref="tree" :load="loadNode" node-key="id" lazy :highlight-current="true" :default-expanded-keys="[treeData[0].id]" :props="defaultProps" v-if="treeData.length" :expand-on-click-node="false" @node-click="handleNodeClick">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ data.type===4? data.name+' '+data.grade :data.name }}</span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="18">
        <div class="inner-bottom-exp-inner" style="height: 100%;">
          <!--没有组织的时候提示信息-->
          <div v-if="!treeData.length" style="margin: 300px auto;text-align: center; font-weight: 700;font-size: 18px;color: #C1CAD1;">你还没有一个组织，从左侧开始新建组织</div>
          <!--校级、院级详情模块-->
          <section v-if="schoolData&& currentActiveNodeType==='school'" class="cell">
            <section class="clear cell-top">
              <div class="clear">
                <div class="fl cell-top-title">{{schoolData.name}}</div>
              </div>
              <div class="clear cell-caption">简称：{{schoolData.sn}}</div>
            </section>
            <div class="dy-line mt20 mb10"></div>
            <div v-if="!schoolData.organizationVoList" style="margin: 300px auto;text-align: center; font-weight: 700;font-size: 18px;color: #C1CAD1;">你还没有下级，从右侧开始新建学院</div>
            <section :key="index" v-for="(item, index) in schoolData.organizationVoList">
              <section class="clear">
                <div class="fl">
                  <div class="clear">
                    <div style="font-size: 14px;color: #333;line-height: 30px;font-weight: 700;">{{item.name}}</div>
                    <div style="font-size: 12px;color: #999;font-weight: 700">{{item.type | typeToDesc}}：{{item.num}}</div>
                  </div>
                </div>
                <div class="fr vm">

                </div>
              </section>
              <div class="dy-line mt20 mb10"></div>
            </section>
          </section>
          <!-- 院级、专业详情模块 -->
          <section v-if="collegeData&&currentActiveNodeType==='college'" class="cell">
            <section class="clear cell-top">
              <div class="clear">
                <div class="fl cell-top-title">{{collegeData.name}}</div>
              </div>
              <div class="clear cell-caption">简称：{{collegeData.sn}}</div>
            </section>
            <div class="dy-line mt20 mb10"></div>
            <div v-if="!collegeData.organizationVoList" style="margin: 300px auto;text-align: center; font-weight: 700;font-size: 18px;color: #C1CAD1;">你还没有下级，从右侧开始新建专业</div>
            <section :key="index" v-for="(item, index) in collegeData.organizationVoList">
              <section class="clear">
                <div class="fl">
                  <div class="clear">
                    <div style="font-size: 14px;color: #333;line-height: 30px;font-weight: 700;">{{item.name}}</div>
                    <div style="font-size: 12px;color: #999;font-weight: 700">{{item.type | typeToDesc}}：{{item.num}}</div>
                  </div>
                </div>
                <div class="fr vm">
                </div>
              </section>
              <div class="dy-line mt20 mb10"></div>
            </section>
          </section>
          <!-- 专业、班级详情模块 -->
          <section v-if="marjorData&&currentActiveNodeType==='major'" class="cell">
            <section class="clear cell-top">
              <div class="clear">
                <div class="fl cell-top-title">{{marjorData.name}}</div>
              </div>
              <div class="clear cell-caption">简称：{{marjorData.sn}}</div>
            </section>
            <div class="dy-line mt20 mb10"></div>
            <div v-if="!marjorData.organizationVoList" style="margin: 300px auto;text-align: center; font-weight: 700;font-size: 18px;color: #C1CAD1;">你还没有下级，从右侧开始新建班级</div>
            <section :key="index" v-for="(item, index) in marjorData.organizationVoList">
              <section class="clear">
                <div class="fl">
                  <div class="clear">
                    <div style="font-size: 14px;color: #333;line-height: 30px;font-weight: 700;">{{item.name}}</div>
                    <div style="font-size: 12px;color: #999;font-weight: 700">{{item.type | typeToDesc}}：{{item.num}}</div>
                  </div>
                </div>
                <div class="fr vm">
                  <div class="fl exp ml10">辅导员：<span v-if='!item.teacherVOList' style="color:red;">未分配</span><span v-for="(childItem, clildindex) in item.teacherVOList" :key="clildindex">{{childItem.name}} <i v-if="clildindex!=(item.teacherVOList.length-1)&&item.teacherVOList.length>1">、</i></span></div>
                  <el-button class="fl exp ml10" type="text" @click="showCounsellorDialog(item)">辅导员管理</el-button>
                </div>
              </section>
              <div class="dy-line mt20 mb10"></div>
            </section>
          </section>
          <!--班级详情模块-->
          <section v-if="classData&&currentActiveNodeType==='class'" class="cell">
            <section class="clear cell-top">
              <div class="fl cell-top-title">{{classData.name}}</div>

            </section>
            <div class="dy-line mt20 mb10"></div>
            <section class="content-search" style="margin-bottom: 10px!important;">
              <div class="fl" style="line-height: 26px;color: #333;font-size: 16px;">学生名单</div>
              <div class="fr ml20">
                <el-button size="mini" type="primary" @click="search">搜索</el-button>
              </div>
              <div class="fr ml20">
                <el-input size="mini" v-model="sear.keyword" placeholder="请输入工号/学号或者姓名搜索"></el-input>
              </div>
            </section>
            <section class="content-list">
              <el-table :data="studentDatas" stripe style="width: 100%">
                <el-table-column prop="date" label="序号" width="50" type="index">
                  <template slot-scope="scope"><span>{{scope.$index+(pageIndex - 1) * pageSize + 1}} </span></template>
                </el-table-column>
                <el-table-column prop="name" label="姓名" width="120"></el-table-column>
                <el-table-column prop="sn" label="工号/学号"></el-table-column>
                <el-table-column prop="roleName" label="角色名称">
                  <template slot-scope="scope"><span>学生{{scope.row.valid===1?'（正常）':'（冻结）'}} </span></template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template slot-scope="scope">
                    <el-button @click="viewStudentInfo(scope.row.sn)" type="text" size="mini">查看</el-button>
                    <!-- <el-button @click="updateStudentInfo(scope.row.id)" type="text" size="mini">修改</el-button>
                    <el-button @click="moveStudentInfo(scope.row.id)" type="text" size="mini">移动</el-button> -->
                    <!-- <el-button @click="deleteStudentInfo(scope.row.id)" class="text-error" type="text" size="mini">删除</el-button> -->
                  </template>
                </el-table-column>
              </el-table>
            </section>
            <section class="content-page">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageIndex" :page-sizes="[10, 15, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
              </el-pagination>
            </section>
          </section>
        </div>
      </el-col>
    </el-row>
    <!-- 辅导员管理 -->
    <el-dialog title="辅导员管理" :visible.sync="dialogCounsellor" width="50%" class="counsellorDialog" :before-close="handleCounsellorClose">
      <p>班级名称：{{currentClass.name}}</p>
      <p style="font-size: 12px; color: rgb(153, 153, 153);">每个班级请至少分配一个辅导员</p>
      <p>当前辅导员姓名：</p>
      <el-table v-if="dialogCounsellorTableData.length" :data="dialogCounsellorTableData" style="width:50%" :show-header='false'>
        <el-table-column>
          <template slot-scope="scope">
            {{`${scope.row.name} ${scope.row.sn}`}}
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-button type="text" @click="delCounsellor(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <p v-else style="color:red;">未分配</p>
      <el-button type="text" @click="showAddCounsellor=true">+添加辅导员</el-button>
      <div v-if="showAddCounsellor">
        <el-autocomplete style="width:50%" size="small" v-model="selectCounsellor" :trigger-on-focus="false" value-key="nameAndSn" :fetch-suggestions="querySearchAsync" placeholder="请输入姓名或工号" @select="handleSelectCounsellor"></el-autocomplete>
        <el-button :disabled="addDisabled" size="small" @click="addCounsellor">添加</el-button>
      </div>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogCounsellor = false">取 消</el-button>
        <el-button type="primary" @click="dialogCounsellor = false">保 存</el-button> -->
      </span>
    </el-dialog>

    <!--学生移动班级对话框-->
    <el-dialog title="移动" :visible.sync="dialogMove">
      <el-form :model="moveForm" :rules="moveRules" ref="moveForm" label-width="95px">
        <el-form-item label="原始班级">
          <span>{{moveForm.originalClass}}</span>
        </el-form-item>
        <section class="clear">
          <el-form-item label="移动至">
            <el-select v-model="moveForm.collegeId" placeholder="请选择学院" @change="getMajorsByCollege">
              <el-option :key="index" v-for="(item,index) in  colleges" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select v-model="moveForm.majorId" placeholder="请选择专业" @change="getClasssByMajor">
              <el-option :key="index" v-for="(item,index) in  majors" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select v-model="moveForm.clazzId" placeholder="请选择班级">
              <el-option :key="index" v-for="(item,index) in  classs" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </section>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogMove = false">取 消</el-button>
        <el-button type="primary" @click="saveMove('moveForm')">保 存</el-button>
      </div>
    </el-dialog>
    <!--批量新增学生对话框-->
    <el-dialog title="批量新增" :visible.sync="dialogBatchAddStudent" width="30%" @closed="clearBatchAddStudent">
      <section class="content-search">
        <el-form>
          <el-form-item label="上传：">
            <el-upload class="file-uploader" ref="upload" :action="uploadUrl" :auto-upload="false" :file-list="fileList" :on-success="handleUploadSuccess" :on-change="onFileChange">
              <el-button slot="trigger" size="small"><i class="el-icon-upload2"></i> 上传文件</el-button> <a target="_blank" :href="downloadTemplateUrl" class="download-template">下载模板</a>
              <div slot="tip" class="el-upload__tip">支持上传文件格式：xls/xlsx，单个文档不大于8M</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="角色：">
            <el-select v-model="batchAddStudentRoleId" size="small" placeholder="请选择" disabled="true">
              <el-option v-for="item in [{id:1,name:'学生'}]" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
            <div>此处角色默认为学生</div>
          </el-form-item>
        </el-form>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogBatchAddStudent = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload">保 存</el-button>
      </span>
    </el-dialog>
    <!--新增学生失败对话框-->
    <el-dialog title="批量新增" :visible.sync="dialogBatchAddError" width="30%">
      <section class="content-search">
        <div style="text-align:center">
          <i class="el-icon-error" style="color: red;
    font-size: 20px;
    vertical-align: middle;
    margin-right: 10px;"></i>上传失败！
        </div>
        <div style="margin: 15px 0;color: #3a8ee6cc;">
          重复人数：{{duplicateSns.length}}
        </div>
        <div>
          <div :key="index" v-for="(item,index) in duplicateSns" style="width:33%;display:inline-block">{{item}}</div>
        </div>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogBatchAddError = false">取 消</el-button>
        <el-button type="primary" @click="dialogBatchAddError = false">保 存</el-button>
      </span>
    </el-dialog>
    <StudentInfo :type="studentInfoType" :data="studentInfoData" :show="dialogStudentInfo" :changeStatus="changeStudentInfoDialogStatus" :loadStudents="getStudentData"></StudentInfo>
  </section>
</template>

<script>
import { people, common, college } from '@/api/index'
import { prodUrl } from '@/tools/utils'
import StudentInfo from '@/pages/main/routes/peopleManagement/StudentInfo'
import * as R from 'ramda'
export default {
  name: 'student',
  data () {
    return {
      dialogCounsellor: false,
      currentClass: {
        id: null,
        name: null
      },
      dialogCounsellorTableData: [],
      addDisabled: true,
      showAddCounsellor: false,
      selectCounsellor: null,
      currentSelectCounsellor: {},
      restaurants: [],
      // 组织树相关数据
      treeData: [],
      defaultProps: {
        children: 'organizationVoList',
        label: 'name',
        isLeaf: 'leaf'
      },
      currentActiveNodeType: 'school',
      currentActiveNodeParentData: {
        id: undefined
      },
      currentActiveNodeData: {
        id: undefined
      },
      currentActiveNode: {
        data: {
          id: undefined
        }
      },
      grades: [], // 年级options

      schoolData: null, // 学校数据
      collegeData: null, // 学院数据
      marjorData: null, // 专业数据
      classData: null, // 班级数据

      // 各种对话框显示状态
      dialogMove: false,
      dialogBatchAddError: false,
      dialogBatchAddStudent: false,
      dialogStudentInfo: false,
      // 学生相关操作需要的数据
      studentInfoData: {
        otherData: {},
        studentBasic: {},
        studentContact: {},
        studentEducation: {},
        studentParents: [],
        studentrelatives: [],
        studentFriends: [],
        sn: '',
        classId: undefined,
        picUrl: '',
        name: '',
        gender: 1,
        nationId: undefined,
        politicalStatus: undefined,
        nativePlaceId: undefined,
        idType: undefined,
        role: '学生',
        idNumber: '',
        religion: '',
        birthDate: '',
        dietaryHabit: '',
        enterDate: '',
        campusId: undefined,
        graduateDate: '',
        hobby: '',
        dorm: '',
        college: '',
        major: '',
        grade: '',
        class: '',
        educationLevel: '',
        studentLength: '',
        phone: '',
        wechat: '',
        email: '',
        qq: '',
        homeContact: '',
        homePhone: '',
        homeAddress: '',
        homePostcode: ''
      },
      studentInfoType: 'create',
      // 表单数据模型
      moveForm: {
        originalClass: '',
        clazzId: undefined,
        collegeId: undefined,
        majorId: undefined,
        studentId: undefined
      },
      // 表单验证规则
      moveRules: {
        collegeId: [
          { required: true, message: '请选择学院', trigger: ['change', 'blue'] }
        ],
        majorId: [
          { required: true, message: '请选择专业', trigger: ['change', 'blue'] }
        ],
        clazzId: [
          { required: true, message: '请选择班级', trigger: ['change', 'blue'] }
        ]
      },

      // 学生信息table 需要的数据
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      sear: {
        keyword: ''
      },
      studentDatas: [],
      // 移动学生dialog 相关下拉列表options
      colleges: [],
      majors: [],
      classs: [],
      // 批量添加学生需要的数据
      fileList: [], // 文件列表
      batchAddStudentRoleId: 1, // 批量上传学生角色id
      duplicateSns: [], // 批量上传重复学号
      downloadTemplateUrl: './templates/批量新增学生模板.xlsx'
    }
  },
  components: {
    StudentInfo: StudentInfo
  },
  created () {
    this.getSchoolOrganization()
  },
  computed: {
    uploadUrl: function () {
      let classId = this.currentActiveNode ? this.currentActiveNode.data.id : ''
      return prodUrl(`./api/student/uploadStudentExcel/${classId}`)
    }
  },
  watch: {
    selectCounsellor (newval, oldval) {
      if (!newval) {
        this.currentSelectCounsellor = {}
        this.addDisabled = true
      }
    }
  },
  methods: {
    getAllGrade () {
      people()._getAllGrade().then((res) => {
        if (res.status) {
          this.grades = res.data
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    // 显示辅导员弹窗
    showCounsellorDialog (classInfo) {
      this.dialogCounsellorTableData = []
      this.dialogCounsellor = true
      this.currentClass.id = classInfo.id
      this.currentClass.name = classInfo.name
      if (classInfo.teacherVOList) {
        this.dialogCounsellorTableData.push(...classInfo.teacherVOList)
      } else {
        this.dialogCounsellorTableData = []
      }
    },
    // 辅导员管理弹窗关闭
    handleCounsellorClose () {
      this.selectCounsellor = null
      this.showAddCounsellor = false
      this.dialogCounsellor = false
      this.currentSelectCounsellor = {}
      this.addDisabled = true
    },
    // 搜索辅导员
    querySearchAsync (queryString, cb) {
      if (queryString) {
        college()._fuzzyQueryUser(
          {
            name: queryString
          }
        ).then(res => {
          this.restaurants = []
          if (res.status && res.data) {
            res.data.forEach(item => {
              let newObj = Object.assign(item, {
                nameAndSn: `${item.name} ${item.sn}`
              })
              this.restaurants.push(newObj)
            })

            cb(this.restaurants)
          } else {
            cb(this.restaurants)
          }
        })
      } else {
        this.restaurants = []
        this.currentSelectCounsellor = {}
        this.selectCounsellor = null
        this.addDisabled = true
        cb(this.restaurants)
      }
    },
    handleSelectCounsellor (selectInfo) {
      this.currentSelectCounsellor = selectInfo
      this.addDisabled = false
    },
    //  查询辅导员列表
    getCounsellorList () {
      college()._getInstructorById(this.currentClass.id).then(res => {
        this.dialogCounsellorTableData = []
        if (res.status) {
          this.dialogCounsellorTableData.push(...res.data)
        }
      })
    },
    // 添加辅导员
    addCounsellor () {
      let isHasRepeat = this.dialogCounsellorTableData.filter(item => {
        return item.userId === this.currentSelectCounsellor.userId
      })
      if (isHasRepeat.length) {
        this.$message.warning('请不要重复添加！')
      } else {
        college()._addInstructor(
          {
            'name': null,
            'organizationId': this.currentClass.id,
            'roleId': this.currentSelectCounsellor.roleId,
            'sn': null,
            'userId': this.currentSelectCounsellor.userId
          }
        ).then(res => {
          if (res.status) {
            this.$message.success('添加辅导员成功！')
            this.selectCounsellor = null
            this.getCounsellorList()
            this.getMajorData(this.currentActiveNodeData.id, this.currentActiveNodeData.type)
          }
        })
      }
    },
    delCounsellor (rowData) {
      this.$confirm('你确认删除该辅导员么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        college()._deleteInstructor(
          {
            'name': null,
            'organizationId': this.currentClass.id,
            'roleId': rowData.roleId,
            'sn': null,
            'userId': rowData.userId
          }
        ).then(res => {
          if (res.status) {
            this.$message.success('删除辅导员成功！')
            this.getCounsellorList()
            this.getMajorData(this.currentActiveNodeData.id, this.currentActiveNodeData.type)
          }
        })
      }).catch(() => {

      })
    },
    loadNode (node, resolve) {
      if (node.level === 0) {
        return resolve(node.data)
      }
      if (node.level === 1) {
        if (node.data.organizationVoList) {
          return resolve(node.data.organizationVoList)
        } else {
          return resolve([])
        }
      }
      people()._getOrganization(node.data.id, node.data.type).then((res) => {
        if (res.status) {
          resolve(res.data.organizationVoList ? res.data.organizationVoList : [])
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getSchoolOrganization () {
      people()._getSchoolOrganization().then((res) => {
        if (res.status) {
          if (res.data) {
            this.treeData = [res.data]
            this.schoolData = res.data
            this.currentActiveNodeData = res.data
          }
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getSchoolData () {
      return people()._getSchoolOrganization().then((res) => {
        if (res.status) {
          this.schoolData = res.data
          this.currentActiveNodeData = res.data
          return res
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getCollegeData (id, type) {
      people()._getOrganization(id, type).then((res) => {
        if (res.status) {
          this.collegeData = res.data
          this.currentActiveNodeData = res.data
          return res
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getMajorData (id, type) {
      people()._getOrganization(id, type).then((res) => {
        if (res.status) {
          this.marjorData = res.data
          this.currentActiveNodeData = res.data
          return res
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getClassData (id, type) {
      people()._getOrganization(id, type).then((res) => {
        if (res.status) {
          this.classData = res.data
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getStudentData () {
      people()._findByClassId({
        clazzId: this.classData.id,
        filterValue: this.sear.keyword,
        orderByColumn: '',
        orderByType: '',
        pageNum: this.pageIndex,
        pageSize: this.pageSize
      }).then((res) => {
        if (res.status) {
          this.studentDatas = res.data.pageData
          this.totalCount = res.data.totalCount
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    handleNodeClick (data, node) {
      if (data.type === 0) {
        this.getSchoolData()
        this.currentActiveNodeParentData = node.parent.data
        this.currentActiveNodeData = node.data
        this.currentActiveNodeType = 'school'
      } else if (data.type === 1) {
        this.getCollegeData(data.id, data.type)
        this.currentActiveNodeParentData = node.parent.data
        this.currentActiveNodeData = node.data
        this.currentActiveNodeType = 'college'
      } else if (data.type === 2) {
        this.getMajorData(data.id, data.type)
        this.currentActiveNodeParentData = node.parent.data
        this.currentActiveNodeData = node.data
        this.currentActiveNodeType = 'major'
      } else if (data.type === 4) {
        this.classData = node.data
        this.currentActiveNodeParentData = node.parent.data
        this.currentActiveNodeData = node.data
        this.currentActiveNode = node
        this.currentActiveNodeType = 'class'
        this.getStudentData()
      }
    },
    saveMove (formName) {
      this.$refs[formName].validate((valid) => {
        delete this.moveForm.originalClass
        if (valid) {
          people()._moveStudent({
            ...this.moveForm
          }).then((res) => {
            if (res.status) {
              this.$message.success('学生移动成功')
              this.dialogMove = false
              this.getStudentData()
            } else {
              this.$message.error(res.message)
            }
          }).catch((err) => {
            this.$message.error(err)
          })
        } else {
          return false
        }
      })
    },
    search () {
      this.pageIndex = 1
      this.getStudentData()
    },
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
      this.getStudentData()
    },
    handleCurrentChange (pageIndex) {
      this.pageIndex = pageIndex
      this.getStudentData()
    },
    addStudent () {
      this.studentInfoType = 'create'

      this.studentInfoData = {
        sn: '',
        classId: undefined,
        picUrl: '',
        name: '',
        gender: 1,
        nationId: undefined,
        politicalStatus: undefined,
        nativePlaceId: undefined,
        idType: undefined,
        role: '学生',
        idNumber: '',
        religion: '',
        birthDate: '',
        dietaryHabit: '',
        enterDate: '',
        campusId: undefined,
        graduateDate: '',
        hobby: '',
        dorm: '',
        college: '',
        major: '',
        grade: '',
        class: '',
        educationLevel: '',
        studentLength: '',
        phone: '',
        wechat: '',
        email: '',
        qq: '',
        homeContact: '',
        homePhone: '',
        homeAddress: '',
        homePostcode: ''
      }
      this.studentInfoData.college = this.currentActiveNode.parent.parent.data.name
      this.studentInfoData.major = this.currentActiveNode.parent.data.name
      this.studentInfoData.grade = this.currentActiveNode.data.grade
      this.studentInfoData.class = this.currentActiveNode.data.name
      this.studentInfoData.classId = this.currentActiveNode.data.id
      this.studentInfoData.role = '学生'

      this.changeStudentInfoDialogStatus()
    },
    changeStudentInfoDialogStatus () {
      this.dialogStudentInfo = !this.dialogStudentInfo
    },
    // 查看学生信息
    viewStudentInfo (studentId) {
      this.studentInfoType = 'view'
      // people()._findStudentInfoById(studentId).then((res) => {
      //   if (res.status) {
      //     this.studentInfoData = res.data
      //     this.studentInfoData.college = this.currentActiveNode.parent.parent.data.name
      //     this.studentInfoData.major = this.currentActiveNode.parent.data.name
      //     this.studentInfoData.grade = this.currentActiveNode.data.grade
      //     this.studentInfoData.class = this.currentActiveNode.data.name
      //     this.studentInfoData.role = '学生'
      //     this.changeStudentInfoDialogStatus()
      //   } else {
      //     this.$message.error(res.message)
      //   }
      // }).catch((err) => {
      //   this.$message.error(err)
      // })
      common()._managerGetStudentInfoBySn(studentId).then(res => {
        if (res.status) {
          // 初始化函数
          // 获取学生基本信息
          this.studentInfoData.otherData = res.data
          this.studentInfoData.studentBasic = res.data.studentBasic
          this.studentInfoData.studentContact = res.data.studentContact
          this.studentInfoData.studentEducation = res.data.studentEducation
          this.studentInfoData.studentParents = R.filter((item) => { return item.type === 0 }, res.data.studentFamilies)
          this.studentInfoData.studentrelatives = R.filter((item) => { return item.type === 1 }, res.data.studentFamilies)
          this.studentInfoData.studentFriends = R.filter((item) => { return item.type === 2 }, res.data.studentFamilies)

          // 计算乘车区间
          if (this.studentInfoData.studentBasic.departurePlace === null) {
            this.studentInfoData.studentBasic.departurePlace = ''
          }
          if (this.studentInfoData.studentBasic.destinationPlace === null) {
            this.studentInfoData.studentBasic.destinationPlace = ''
          }
          this.studentInfoData.studentBasic.rideRange = this.studentInfoData.studentBasic.departurePlace + '-' + this.studentInfoData.studentBasic.destinationPlace
          // 处理时间
          if (this.studentInfoData.studentBasic.birthDate) {
            this.studentInfoData.studentBasic.birthDate = this.$moment(this.studentInfoData.studentBasic.birthDate).format('YYYY-MM-DD')
          }
          if (this.studentInfoData.studentEducation.enterDate) {
            this.studentInfoData.studentEducation.enterDate = this.$moment(this.studentInfoData.studentEducation.enterDate).format('YYYY-MM-DD')
          }
          if (this.studentInfoData.studentEducation.graduateDate) {
            this.studentInfoData.studentEducation.graduateDate = this.$moment(this.studentInfoData.studentEducation.graduateDate).format('YYYY-MM')
          }

          // 处理boolbean
          if (this.studentInfoData.studentEducation.absentee !== null) {
            this.studentInfoData.studentEducation.absentee = this.studentInfoData.studentEducation.absentee ? '是' : '否'
          }
          if (this.studentInfoData.studentEducation.atSchool !== null) {
            this.studentInfoData.studentEducation.atSchool = this.studentInfoData.studentEducation.atSchool ? '是' : '否'
          }

          this.changeStudentInfoDialogStatus()
        }
      })
    },
    updateStudentInfo (studentId) {
      this.studentInfoType = 'update'

      people()._findStudentInfoById(studentId).then((res) => {
        if (res.status) {
          this.studentInfoData = res.data
          this.studentInfoData.college = this.currentActiveNode.parent.parent.data.name
          this.studentInfoData.major = this.currentActiveNode.parent.data.name
          this.studentInfoData.grade = this.currentActiveNode.data.grade
          this.studentInfoData.class = this.currentActiveNode.data.name
          this.studentInfoData.role = '学生'
          this.changeStudentInfoDialogStatus()
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    moveStudentInfo (studentId) {
      this.dialogMove = true
      this.moveForm.collegeId = undefined
      this.moveForm.majorId = undefined
      this.moveForm.clazzId = undefined
      this.moveForm.studentId = studentId
      this.moveForm.originalClass = this.currentActiveNode.parent.parent.data.name + ' / ' + this.currentActiveNode.parent.data.name + ' / ' + this.currentActiveNode.data.name

      people()._getColleges().then((res) => {
        if (res.status) {
          this.colleges = res.data
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getMajorsByCollege (collegeId) {
      people()._getMajorsByCollege(collegeId).then((res) => {
        if (res.status) {
          this.majors = res.data
          this.moveForm.majorId = undefined
          this.moveForm.clazzId = undefined
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getClasssByMajor (majorId) {
      people()._getClassesByMajor(majorId).then((res) => {
        if (res.status) {
          this.classs = res.data
          this.moveForm.clazzId = undefined
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    deleteStudentInfo (studentId) {
      this.$confirm('此操作将永久删除学生, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        people()._deleteStudent(studentId).then((res) => {
          if (res.status) {
            this.$message.success('删除学生信息成功')
            this.getStudentData()
          } else {
            this.$message.error(res.message)
          }
        }).catch((err) => {
          this.$message.error(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    onFileChange (file) {
      this.fileList = []
      let isLt8M = file.size / 1024 / 1024 < 8

      let suffix = file.name.split('.')[1]

      if (suffix !== 'xls' && suffix !== 'xlsx') {
        this.$message.error('上传文件只能是 xls|xlsx 格式!')
        return false
      }

      if (!isLt8M) {
        this.$message.error('上传文件大小不能超过 8MB!')
        return false
      }

      this.fileList = [file]
    },
    submitUpload () {
      if (this.fileList.length === 0) {
        this.$message.warning('请选择要上传的文件!')
        return false
      }
      this.$refs.upload.submit()
    },
    clearBatchAddStudent () {
      this.fileList = []
    },
    handleUploadSuccess (res, file, fileList) {
      if (res.status && res.data && res.data.length === 0) {
        this.$message.success('批量上传成功')
        this.dialogBatchAddStudent = false
        this.getStudentData()
      } else if (res.status && res.data && res.data.length > 0) {
        this.duplicateSns = res.data
        this.dialogBatchAddError = true
        setTimeout(() => {
          this.fileList = []
        })
      } else {
        this.$message.error(res.message)
        setTimeout(() => {
          this.fileList = []
        })
      }
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  },
  filters: {
    typeToDesc: function (value) {
      switch (value) {
        case 1:
          value = '专业数'
          break
        case 2:
          value = '班级数'
          break
        case 4:
          value = '学生数'
          break
        default:
          value = '未知类型'
      }
      return value
    }
  }
}
</script>
<style  lang="less"  scoped>
.short-input {
  width: 200px;
}
.file-uploader i {
  color: gray;
  font-size: 15px;
  margin-right: 5px;
  vertical-align: middle;
}
.file-uploader .download-template {
  margin: 15px;
  color: #3a8ee6;
}
.counsellorDialog {
  /deep/.el-table td {
    padding: 0px;
  }
}
</style>
